package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    //多表操作 必须加事务
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        // 涉及多表操作了（事务注意是针对增删改）
        // 1.保存套餐的基本信息到套餐表 -> setmeal
        // insert into 表 values ?????
        this.save(setmealDto);
        // 2.保存套餐与菜品关系到关系表 -> setmeal_dish
        // 思路：获取套餐的菜品列表，遍历这个列表，把套餐的ID赋值进去
        //得到菜品列表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            //把套餐的ID赋值
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }


    //套餐删除的自定义方法

    /**
     * @param ids
     */
    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getId, ids);
        queryWrapper.in(Setmeal::getStatus, "1");

        int count = this.count(queryWrapper);
        if (count > 0) {
            //status就是表中的套餐使用状态
            //如果正在售卖 就不能删除
            throw new CustomException("套餐正在售卖,不能删除!!!");
        }
        //没再售卖的话就删除
        this.removeByIds(ids);
        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(wrapper);
    }
}
